//--- Projeto Domus
// interactionsource.com
// Koji Pereira, Andre Veloso e Marcos Paulo

/*
 Projeto Domus
 interactionsource.com
 Koji Pereira, Andre Veloso e Marcos Paulo

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/


package com.interactionsource.gui;

import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.IOException;

import javax.swing.JDesktopPane;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;

import com.interactionsource.control.Controller;
import com.interactionsource.control.Manager;


public class InterfacePrincipal extends JFrame implements ActionListener {

	private static final long serialVersionUID = 1L;

	JDesktopPane desktop;

	JFileChooser fc;

	private Manager manager;
	
	private Controller controller;

	int portasOSC = 6000;

	public InterfacePrincipal( Manager manager, Controller controller  )  {
		
		super( "Project Virtual IO " + "v0.0.1");

		//Make the big window be indented 50 pixels from each edge
		//of the screen.
		int inset = 50;
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		setBounds(inset, inset,
				screenSize.width  - inset*2,
				screenSize.height - inset*2);

		//Set up the GUI.
		desktop = new JDesktopPane(); //a specialized layered pane
		//createFrame(); //create first "window"
		setContentPane(desktop);
		setJMenuBar(createMenuBar());

		desktop.setDragMode(JDesktopPane.LIVE_DRAG_MODE);

		//Create a file chooser
		fc = new JFileChooser();

		//Uncomment one of the following lines to try a different
		//file selection mode.  The first allows just directories
		//to be selected (and, at least in the Java look and feel,
		//shown).  The second allows both files and directories
		//to be selected.  If you leave these lines commented out,
		//then the default mode (FILES_ONLY) will be used.
		//
		//fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		//fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);        


		this.manager = manager;
		this.controller  = controller ;
	}

	protected JMenuBar createMenuBar() {   

		//Create the menu bar.
		JMenuBar menuBar = new JMenuBar();

		//Build the first menu
		JMenu menu = new JMenu("File");
		menu.setMnemonic(KeyEvent.VK_A);
		menu.getAccessibleContext().setAccessibleDescription(
		"The only menu in this program that has menu items");
		menuBar.add(menu);

		JMenuItem menuItem = new JMenuItem("Open layout",
				KeyEvent.VK_T);
		menuItem.setAccelerator(KeyStroke.getKeyStroke(
				KeyEvent.VK_O, ActionEvent.CTRL_MASK));
		menuItem.setActionCommand("open");
		menuItem.addActionListener(this);
		menu.add(menuItem);

		menuItem = new JMenuItem("Save layout",
				KeyEvent.VK_T);
		menuItem.setAccelerator(KeyStroke.getKeyStroke(
				KeyEvent.VK_S, ActionEvent.CTRL_MASK));
		menuItem.setActionCommand("save");
		menuItem.addActionListener(this);
		menu.add(menuItem);

		menu.addSeparator();

		menuItem = new JMenuItem("Exit",
				KeyEvent.VK_T);
		menuItem.setAccelerator(KeyStroke.getKeyStroke(
				KeyEvent.VK_Q, ActionEvent.CTRL_MASK));
		menuItem.setActionCommand("exit");
		menuItem.addActionListener(this);
		menu.add(menuItem);



		//Build second menu in the menu bar.
		menu = new JMenu("Add Input Device");
		menu.setMnemonic(KeyEvent.VK_N);
		menu.getAccessibleContext().setAccessibleDescription(
		"This menu does nothing");
		menuBar.add(menu);

		menuItem = new JMenuItem("WiimoteOSC",
				KeyEvent.VK_T);
		menuItem.setActionCommand("add input device");
		menuItem.addActionListener(this);
		menu.add(menuItem);	      


		return menuBar;


	}

	//React to menu selections.
	public void actionPerformed(ActionEvent e) {
		if ("open".equals(e.getActionCommand())) { //open

			int returnVal = fc.showOpenDialog(this);

			if (returnVal == JFileChooser.APPROVE_OPTION) {
				File file = fc.getSelectedFile();


				try {
					System.out.println("InterfacePrincipal - Escolhido: " + file.getName());
					System.out.println("InterfacePrincipal - canonical path: " + file.getCanonicalPath() );
					System.out.println("InterfacePrincipal - Absolute path: " + file.getAbsolutePath() );
					System.out.println("InterfacePrincipal - Diretorio " + file.getParent());

					this.manager.resetConfig();

					//manager.readConfigFile("/Users/andrevj/Desktop/TESTE");
					//manager.saveConfigFile("/Users/andrevj/Desktop/TESTESAIDA");

					//this.manager.setPathArquivosConfig("D:\\DropBox\\My Dropbox\\Projeto Circo\\Java\\Teste_wiigee\\config\\");
					//this.manager.readConfigFile("D:\\DropBox\\My Dropbox\\Projeto Circo\\Java\\Teste_wiigee\\config\\TESTE_WIN_GESTOS");

					this.manager.setPathArquivosConfig(file.getParent() + file.separatorChar);

					if ( this.manager.readConfigFile(file.getCanonicalPath()) == 0 ) {

						for (int i=0; i< this.manager.getWiimoteOSCDevicesCount(); i++) {

							adcionaWiimoteOSCFrame(i+1, this.manager.getWiimoteOSCDeviceAt(i).getOscPort());
						}							

					} else {
						//Erro na leitura do arquivo

						//custom title, error icon
						JOptionPane.showMessageDialog(this,
								"File \"" + file.getName() + "\" is invalid.",
								"Error reading file",
								JOptionPane.ERROR_MESSAGE);
						return;
					}

				} catch (IOException e1) {
					e1.printStackTrace();
					return;
				}
			} else {
				System.out.println("Open command cancelled by user.");
				return;
			}

		} else if ("save".equals(e.getActionCommand())) { //save
			int returnVal = fc.showSaveDialog(this);

			if (returnVal == JFileChooser.APPROVE_OPTION) {
				File file = fc.getSelectedFile();

				try {
					System.out.println("InterfacePrincipal - Escolhido: " + file.getName());
					System.out.println("InterfacePrincipal - canonical path: " + file.getCanonicalPath() );
					System.out.println("InterfacePrincipal - Absolute path: " + file.getAbsolutePath() );
					System.out.println("InterfacePrincipal - Diretorio " + file.getParent());

					if (this.manager.saveConfigFile(file.getCanonicalPath()) !=0) {
						//Erro no salvamento do arquivo

						//custom title, error icon
						JOptionPane.showMessageDialog(this,
								"Impossible to save file \"" + file.getName() + "\".",
								"Error saving file",
								JOptionPane.ERROR_MESSAGE);
						return;
					} else {
						//custom title, error icon
						JOptionPane.showMessageDialog(this,
								"File\"" + file.getName() + "\". successfully saved",
								"Saving file...",
								JOptionPane.PLAIN_MESSAGE);
						return;

					}

				} catch (IOException e1) {

					e1.printStackTrace();
					return;
				}

			}


		} else if ("exit".equals(e.getActionCommand())) { //exit
			quit();

		} else if ("add input device".equals(e.getActionCommand())) {

			this.manager.addWiimoteOSCDevice( ++portasOSC );
			adcionaWiimoteOSCFrame(this.manager.getWiimoteOSCDevicesCount(), portasOSC);
		}
	}

	//Create a new internal frame.
	protected void adcionaWiimoteOSCFrame(int idWiimoteOSC, int portaOSC) {


		WiimoteOSCFrame frame = new WiimoteOSCFrame(idWiimoteOSC, portaOSC, this.manager);
		
		//frame.addStartGestureTrainingButtonListener(this.controller);
		//frame.addFinishGestureTrainingButtonListener(this.controller);
		//frame.addSaveGestureButtonListener(this.controller);
		
		frame.setVisible(true); //necessary as of 1.3
		desktop.add(frame);
		try {
			frame.setSelected(true);
		} catch (java.beans.PropertyVetoException e) {}
	}


	/**
	 * Create the GUI and show it.  For thread safety,
	 * this method should be invoked from the
	 * event-dispatching thread.
	 */
	public static void createAndShowGUI( Manager manager, Controller controller ) {
		//Make sure we have nice window decorations.
		JFrame.setDefaultLookAndFeelDecorated(true);

		//Create and set up the window.
		InterfacePrincipal frame = new InterfacePrincipal( manager, controller);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		//Display the window.
		frame.setVisible(true);
	}

	//Quit the application.
	protected void quit() {
		System.exit(0);
	}

}
